package com.jf.exam.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jf.exam.mapper.ExamQuestionMapper;
import com.jf.exam.mapper.ExaminationResulquestionMapper;
import com.jf.exam.mapper.QuestionChoiceMapper;
import com.jf.exam.mapper.QuestionJudgeMapper;
import com.jf.exam.pojo.data.ExamQuestionDO;
import com.jf.exam.pojo.data.QuestionChoiceDO;
import com.jf.exam.pojo.data.QuestionJudgeDO;
import com.jf.exam.pojo.vo.*;
import com.jf.exam.service.ExamQuestionService;
import com.jf.exam.service.ExamService;
import com.jf.exam.service.QuestionService;
import com.jf.exam.utils.AnswerUtils;
import com.jf.exam.utils.PageBean;
import com.jf.exam.utils.QuestionType;
import com.jf.exam.utils.Result;
import com.jf.exam.utils.exception.BusinessException;
import com.jf.exam.utils.exception.PageCodeException;
import com.jf.exam.utils.exception.RestfulPageCodeException;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("questionService")
public class QuestionServiceImpl implements QuestionService {
    @Autowired
    QuestionChoiceMapper questionChoiceMapper;
    @Autowired
    QuestionJudgeMapper questionJudgeMapper;

    @Autowired
    ExamQuestionMapper examQuestionMapper;


    @Autowired
    ExamQuestionService examQuestionService;

    @Autowired
    ExamService examService;


    @Autowired
    ExaminationResulquestionMapper examinationResulquestionMapper;


    //选择题
    @Override
    public PageBean<QuestionListVO> listQuestionChoice(QuestionChoiceVO query) throws Exception {
        //防止页码越界
        Integer count = questionChoiceMapper.countQuestionChoice(query);
        int max = (count + query.getPageSize() - 1) / query.getPageSize();
        if (query.getPageCode() > max) {
            //query.setPageCode(max);
            throw new PageCodeException("越界啦", max);
        }
        PageHelper.startPage(query.getPageCode(), query.getPageSize());
        List<QuestionChoiceDO> choiceDOS = questionChoiceMapper.listQuestionChoice(query);
        System.out.println(choiceDOS);
        ArrayList<QuestionListVO> list = new ArrayList<>();
        for (QuestionChoiceDO qdo : choiceDOS) {
            QuestionListVO vo = new QuestionListVO();
            BeanUtils.copyProperties(vo, qdo);
            vo.setTitle(qdo.getQuestion());
            vo.setPoint(qdo.getScore().intValue());
            vo.setAnswerFacade(AnswerUtils.getAnserFacade(qdo.getType(), qdo.getAnswer()));
            list.add(vo);
        }
        //插件提供的分页信息
        PageInfo<QuestionChoiceDO> info = new PageInfo<>(choiceDOS);

        //根据插件提供的分页信息，构造我们自己的分页信息
        PageBean<QuestionListVO> pageBean = new PageBean<QuestionListVO>(list, info.getPageSize()
                , query.getPageCode(), (int) info.getTotal(), query.getSize());
        return pageBean;
    }

    @Override
    public PageBean<QuestionListVO> listQuestionJudge(QuestionJudgeVO query) throws Exception {
        //防止页码越界
        Integer count = questionJudgeMapper.countQuestionJudge(query);
        int max = (count + query.getPageSize() - 1) / query.getPageSize();
        if (query.getPageCode() > max) {
            //query.setPageCode(max);
            throw new RestfulPageCodeException("越界啦", "/teacher/question/judges/");
        }
        PageHelper.startPage(query.getPageCode(), query.getPageSize());
        List<QuestionJudgeDO> questionJudgeDOS = questionJudgeMapper.listQuestionJudge(query);
        ArrayList<QuestionListVO> list = new ArrayList<>();
        for (QuestionJudgeDO qdo : questionJudgeDOS) {
            QuestionListVO vo = new QuestionListVO();
            BeanUtils.copyProperties(vo, qdo);
            vo.setTitle(qdo.getQuestion());
            vo.setPoint(qdo.getScore().intValue());
            vo.setAnswerFacade(AnswerUtils.getAnserFacade(qdo.getType(), qdo.getAnswer()));
            list.add(vo);
        }

        //插件提供的分页信息
        PageInfo<QuestionJudgeDO> info = new PageInfo<>(questionJudgeDOS);

        //根据插件提供的分页信息，构造我们自己的分页信息
        PageBean<QuestionListVO> pageBean = new PageBean<QuestionListVO>(list, info.getPageSize()
                , query.getPageCode(), (int) info.getTotal(), query.getSize());
        return pageBean;

    }


    //传入试卷id，如果题目添加成功，那么将试卷和题目进行关联
    @Override
    public Result addQuestionJudge(QuestionJudgeVO questionJudgeVO, String examId) throws Exception {
        int count = questionJudgeMapper.addQuestionJudge(questionJudgeVO);
        if (count > 0) {
            if (examId != null) {
                //在试卷管理页面添加的题目，将试卷和题目进行关联
                //试卷id 和 题目id
                System.out.println(questionJudgeVO.getId());
                ExamQuestionVO examQuestionVO = new ExamQuestionVO();
                examQuestionVO.setFkExam(Integer.parseInt(examId));
                examQuestionVO.setFkQuestion(questionJudgeVO.getId());
                examQuestionVO.setFkQtype(3);
                return examQuestionService.addExamQuestion(examQuestionVO, Integer.parseInt(examId), questionJudgeVO.getScore().intValue());
            }
            return Result.getSuccess("添加成功");
        }
        throw new BusinessException("添加失败");
    }

    @Override
    public Result updateQuestionJudge(QuestionJudgeVO questionJudgeVO) {
        int count = questionJudgeMapper.updateQuestionJudge(questionJudgeVO);
        if (count > 0) {
            return Result.getSuccess("更新成功");
        }
        throw new BusinessException("更新失败");
    }

    @Override
    public Result addQuestionChoice(QuestionChoiceVO questionChoiceVO, String examId) throws Exception {
        int count = questionChoiceMapper.addQuestionChoice(questionChoiceVO);
        if (count > 0) {
            if (examId != null) {
                //在试卷管理页面添加的题目，将试卷和题目进行关联
                //试卷id 和 题目id
                System.out.println(questionChoiceVO.getId());
                ExamQuestionVO examQuestionVO = new ExamQuestionVO();
                examQuestionVO.setFkExam(Integer.parseInt(examId));
                examQuestionVO.setFkQuestion(questionChoiceVO.getId());
                examQuestionVO.setFkQtype(questionChoiceVO.getType());
                return examQuestionService.addExamQuestion(examQuestionVO, Integer.parseInt(examId), questionChoiceVO.getScore().intValue());
            }
            return Result.getSuccess("更新成功");
        }
        throw new BusinessException("更新失败");
    }

    @Override
    public Result updateQuestionChoice(QuestionChoiceVO questionChoiceVO) {
        int count = questionChoiceMapper.updateQuestionChoice(questionChoiceVO);
        if (count > 0) {
            return Result.getSuccess("更新成功");
        }
        throw new BusinessException("更新失败");
    }

    @Override
    public PageBean<QuestionManageVO> listQuestionByExam(Integer eid, Integer pageCode, int pageSize, int navigatePages) {
        //1. 根据试卷id查询所有的题目
        ExamQuestionVO examQuestionVO = new ExamQuestionVO();
        examQuestionVO.setFkExam(eid);
        List<ExamQuestionDO> examQuestionDOS = examQuestionMapper.listExamQuestion(examQuestionVO);

        if (examQuestionDOS == null || examQuestionDOS.isEmpty()) {
            return null;
        }


        ArrayList<Integer> choiceIDs = new ArrayList<>();
        ArrayList<Integer> judgeIDs = new ArrayList<>();
        //2. 根据类型筛选id
        for (ExamQuestionDO examQuestionDO : examQuestionDOS) {
            if (examQuestionDO.getFkQtype() == QuestionType.JUDGE) {//判断题
                judgeIDs.add(examQuestionDO.getFkQuestion());
            } else {
                //选择题
                choiceIDs.add(examQuestionDO.getFkQuestion());
            }
        }
        System.out.println(choiceIDs + "" + judgeIDs);
        //因为题目的分成两个表来存储的，所以id会重复，所以需要根据各自的id查询各自的表

        //构造查询条件
        QuestionManageQuery query = new QuestionManageQuery();
        //id
        query.setChoiceIDs(choiceIDs);
        query.setJudgeIDs(judgeIDs);
        //分页条件
        int start = (pageCode - 1) * pageSize;
        query.setStartRecord(start);
        query.setPageSize(pageSize);
        query.setPageCode(pageCode);
        query.setSize(navigatePages);
        List<QuestionManageVO> manageVOS = examQuestionMapper.listExamQuestionByExam(query);

        for (QuestionManageVO manageVO : manageVOS) {
            manageVO.setAnswerFacade(QuestionType.getTypeByNum(Integer.parseInt(manageVO.getType())));
        }

        //总个数是id集合的大小 choiceIDs.size() + judgeIDs.size()
        PageBean<QuestionManageVO> pageBean = new PageBean<QuestionManageVO>(manageVOS,
                query.getPageSize(), query.getPageCode(), examQuestionDOS.size(), query.getSize());
        System.out.println(manageVOS);


        //# 占位符 会以 ? 号占位
        //$ 替换符号
//        String sql =
//                "SELECT * FROM (" +
//                " SELECT qc.id,qc.question,qc.type,qc.score FROM question_choice qc WHERE qc.id IN(1,2) "+
//                " UNION ALL "+
//                " SELECT qj.id,qj.question,qj.type,qj.score FROM question_judge qj WHERE qj.id IN(1,2) "+
//                " )AS tmp LIMIT 0,3 ";
//        //测试
//        List<QuestionManageVO> vos = examQuestionMapper.listExamQuestionByExam2(sql);
//        System.out.println(vos);
        return pageBean;
    }

    /**
     * 返回的数据和列表一样
     */
    @Override
    public Result listAllByType(QuestionBankVO vo) throws Exception {
        //存储所有的题目数据（数据库）
        ArrayList<QuestionListVO> qlvs = new ArrayList<>();
        if (Integer.parseInt(vo.getType()) == QuestionType.JUDGE) {
            //查询判断题
            QuestionJudgeVO judgeVO = new QuestionJudgeVO();
            List<QuestionJudgeDO> judgeDOS = questionJudgeMapper.listQuestionJudge(judgeVO);
            //将数据进行转换
            parsingJudegeQuestion(judgeDOS, qlvs);
        } else {
            //查询选择题
            QuestionChoiceVO choiceVO = new QuestionChoiceVO();
            //单选和多选进行区分
            if (Integer.parseInt(vo.getType()) == QuestionType.SINGLE) {
                choiceVO.setType(QuestionType.SINGLE);
            } else {
                choiceVO.setType(QuestionType.MULTI);
            }
            List<QuestionChoiceDO> choiceDOS = questionChoiceMapper.listQuestionChoice(choiceVO);
            parsingChoiceQuestion(choiceDOS, qlvs);
        }

        //去除重复的数据
        //去除试卷已有的题目数据
        for (int i = 0; i < vo.getTypes().size(); i++) {
            TypesVO typesVO = vo.getTypes().get(i);
            for (int j = 0; j < qlvs.size(); j++) {
                QuestionListVO q = qlvs.get(j);
                if (typesVO.getType().equals(q.getType()) && Integer.parseInt(typesVO.getId()) == q.getId()) {
                    qlvs.remove(j);
                }
            }
        }
        return new Result(Result.CODE_SUCCESS, qlvs);
    }

    @Override
    public Result addExamQuestion(List<ExamQuestionVO> vos, Integer examId) {
        //使用循环添加试卷和题目的关系
        for (ExamQuestionVO vo : vos) {
            int count = examQuestionMapper.addExamQuestion(vo);
            if (count > 0) {
                if (examId != null && examId != 0) {
                    //更新试卷信息
                    int updExamCount = examService.updateExamScore(examId, vo.getScore(), vo.getFkQtype());
                }
            }
        }
        return Result.getSuccess("添加成功");
    }

    @Override
    public Result rate(Integer qid) {
        ExaminationResulquestionVO vo = new ExaminationResulquestionVO();
        vo.setFkQuestion(qid);
        Double rate = examinationResulquestionMapper.rate(vo);
        if (rate == null) {
            return Result.getFailure("获取失败");
        }
        Result result = new Result();
        result.setMsg("获取成功");
        result.setCode(Result.CODE_SUCCESS);
        result.setData((rate*100)+"%");
        return result;
    }

    /**
     * 解析判断题
     */
    public void parsingJudegeQuestion(List<QuestionJudgeDO> judgeDOS, ArrayList<QuestionListVO> qlvs) throws Exception {
        for (QuestionJudgeDO judgeDO : judgeDOS) {
            QuestionListVO vo = new QuestionListVO();
            BeanUtils.copyProperties(vo, judgeDO);
            vo.setTitle(judgeDO.getQuestion());
            vo.setType(judgeDO.getType() + "");
            vo.setPoint(judgeDO.getScore().intValue());
            qlvs.add(vo);
        }
    }

    /**
     * 解析选择题
     */
    public void parsingChoiceQuestion(List<QuestionChoiceDO> choiceDOS, ArrayList<QuestionListVO> qlvs) throws Exception {
        for (QuestionChoiceDO qdo : choiceDOS) {
            QuestionListVO vo = new QuestionListVO();
            BeanUtils.copyProperties(vo, qdo);
            vo.setTitle(qdo.getQuestion());
            vo.setPoint(qdo.getScore().intValue());
            vo.setAnswerFacade(AnswerUtils.getAnserFacade(qdo.getType(), qdo.getAnswer()));
            qlvs.add(vo);
        }
    }


}

